package com.xtxk.contorller;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.xtxk.common.constant.CommonConstant;
import com.xtxk.dto.out.SysUser;
import com.xtxk.utils.result.Result;
import com.xtxk.utils.util.JwtUtil;
import com.xtxk.utils.util.PasswordUtil;
import com.xtxk.utils.util.RedisUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author tiger
 * 首先登录进行 TOKEN授权
 */
@RestController
@Api(tags = "登录")
@RequestMapping(value = "/login")
public class ShiroLoginController {
	
	@Autowired
    private RedisUtil redisUtil;

	@RequestMapping(value = "/authorization", method = RequestMethod.POST)
	@ApiOperation("登录并授权")
	public Result<?> login(@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "password", required = true) String password) {
		String passwordEncode = PasswordUtil.encrypt(name, password, PasswordUtil.Salt);
		if (passwordEncode.equals(CommonConstant.SYS_PASS_WORD)) {
			SysUser sysUser = new SysUser();
			sysUser.setUsername(name);
			sysUser.setPassword(passwordEncode);// 设置加密后的密码
			Map<String, Object> map = new HashMap<>();
			userInfo(sysUser, map);
			return Result.ok(map);
		} else {
			throw new UnauthorizedException();
		}
	}
	
	/**
	 * 缓存用户TOKEN和信息
	 * @param sysUser
	 * @param result
	 */
	private Map<String, Object> userInfo(SysUser sysUser, Map<String, Object> result) {
		String syspassword = sysUser.getPassword();
		String username = sysUser.getUsername();
		// 生成token
		String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
		redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
		redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
		JSONObject obj = new JSONObject();
		obj.put("token", token);
		obj.put("userInfo", sysUser);
		return result;
	}
}
